package org.scratchcrew.web.jsf.myfaces;

import javax.faces.context.FacesContext;

import org.apache.myfaces.application.ViewHandlerSupport;
import org.scratchcrew.web.jsf.CustomViewHandler;

/**
 * Decorator of {@link ViewHandlerSupport}
 * 
 */
public class CustomViewHandlerSupport implements ViewHandlerSupport {
	private ViewHandlerSupport originalViewHandlerSupport;

	public CustomViewHandlerSupport(ViewHandlerSupport viewHandlerSupport) {
		this.originalViewHandlerSupport = viewHandlerSupport;
	}

	@Override
	public String calculateActionURL(FacesContext facesContext, String viewId) {
		String prefix = getViewPrefix(facesContext);
		String truncatedViewId = viewId.substring(prefix.length());
		return originalViewHandlerSupport.calculateActionURL(facesContext,
				truncatedViewId);
	}

	@Override
	public String calculateViewId(FacesContext context, String viewId) {
		String prefix = getViewPrefix(context);
		String prefixedViewId;
		if (viewId.startsWith(prefix)) {
			prefixedViewId = viewId;
		} else {
			prefixedViewId = prefix + viewId;
		}
		return originalViewHandlerSupport.calculateViewId(context,
				prefixedViewId);
	}

	/**
	 * 
	 * @param facesContext
	 *            current faces context
	 * @return prefix defined by
	 *         {@value CustomViewHandler#DEFAULT_VIEW_PREFIX_PARAM_NAME} context
	 *         parameter. If not such parameter is present
	 *         {@value CustomViewHandler#DEFAULT_VIEW_PREFIX} is used.
	 */
	protected String getViewPrefix(FacesContext facesContext) {
		String prefix = facesContext.getExternalContext().getInitParameter(
				CustomViewHandler.DEFAULT_VIEW_PREFIX_PARAM_NAME);
		if (prefix == null) {
			prefix = CustomViewHandler.DEFAULT_VIEW_PREFIX;
		}
		return prefix;
	}

}
